<?php
Yii::import ( 'littlecrm.CRMBaseController' );
class UserController extends CRMBaseController {
	public function actionLogin() {
		$form = new LoginForm ();
		// collect user input data
		if (isset ( $_POST ['LoginForm'] )) {
			$form->attributes = $_POST ['LoginForm'];
			// validate user input and redirect to previous page if valid
			if ($form->validate ()) {
				$this->redirect ( Yii::app ()->user->returnUrl );
			}
		}
		// display the login form
		$this->render ( 'login', array ('form' => $form ) );
	}
	
	public function actionChangePassword() {
		$passwordChangeMeModel = new ChangePasswordForm ();
		if (isset ( $_POST ['ChangePasswordForm'] )) {
			$passwordChangeMeModel->attributes = $_POST ['ChangePasswordForm'];
			if (! $passwordChangeMeModel->validate ()) {
				$this->renderPartial ( 'tabs/_changePasswordForm', array ('passwordChangeMeModel' => $passwordChangeMeModel ), false, true );
			} else {
				$userId = Yii::app ()->user->getId ();
				$me = Users::model ()->findByPk ( $userId );
				$data = Yii::app ()->request->getPost ( 'ChangePasswordForm', null );
				$me->updatePassword ( $data ['newPassword'] );
			}
		}
	}
	
	/**
	 * @todo changeMe Ajax refactoring / own method or action
	 */
	public function actionChangeMe() {
		$userModel = new Users ();
		$passwordChangeMeModel = new ChangePasswordForm ();
		$userId = Yii::app ()->user->getId ();
		$me = $userModel->findByPk ( $userId );
		if (Yii::app ()->request->getIsPostRequest () && null !== ($data = Yii::app ()->request->getPost ( 'Users', null ))) {
			$me->attributes = $data;
			$me->save ();
			//$userModel->updateAll($data, 'users_username=?', array($userId));
		}
		
		if (! Yii::app ()->request->isAjaxRequest) {
			$this->render ( 'changeMe', array ('me' => $me, 'passwordChangeMeModel' => $passwordChangeMeModel ) );
		} else {
			$this->renderPartial ( 'tabs/userData', array ('userModel' => $me, 'passwordFields' => false ), false, true );
		}
	}
	
	public function actionLogout() {
		Yii::app ()->user->logout ();
		$this->redirect ( Yii::app ()->createUrl ( Yii::app ()->user->loginUrl ) );
	}
	
	public function actions() {
		return array (// captcha action renders the CAPTCHA image
		// this is used by the contact page
		'captcha' => array ('class' => 'CCaptchaAction', 'backColor' => 0xEBF4FB ) );
	}
}